package com.chenwang.measure.ui.activity;

import android.app.AlertDialog;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.DialogInterface;
import android.content.Intent;
import android.mtp.MtpConstants;
import android.os.Bundle;
import android.os.Environment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chenwang.measure.MyApp;
import com.chenwang.measure.R;
import com.chenwang.measure.base.BaseActivity;
import com.chenwang.measure.model.Constant;
import com.chenwang.measure.model.ObserverOnNext;
import com.chenwang.measure.model.OkgoNetwork;
import com.chenwang.measure.model.bean.ImgBean;

import com.chenwang.measure.model.bean.WorkBean;
import com.chenwang.measure.model.bean.WorkTaskBean;
import com.chenwang.measure.ui.adapter.MeasureAdapter;
import com.chenwang.measure.ui.adapter.TaskManageAdapter;
import com.chenwang.measure.ui.dialog.TaskBuletoothDialog;
import com.chenwang.measure.utils.BlueConnectTask;
import com.chenwang.measure.utils.BluetoothConnector;
import com.chenwang.measure.utils.BluetoothUtil;
import com.chenwang.measure.utils.FileUtils;
import com.chenwang.measure.utils.MyLogger;
import com.chenwang.measure.utils.MyToast;
import com.chenwang.measure.utils.SharePreferenceUtils;
import com.chenwang.measure.utils.UIUtils;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.Callback;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Progress;
import com.lzy.okgo.model.Response;
import com.lzy.okgo.request.base.Request;

import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

//任务模块 上传下载
public class TaskManageActivity extends BaseActivity implements BaseQuickAdapter.OnItemChildClickListener ,OkgoNetwork.I{


    @BindView(R.id.rv)
    RecyclerView mRv;
    @BindView(R.id.btn_download)
    Button mBtnDownload;   //下载
    @BindView(R.id.btn_uploading)
    Button mBtnUploading;  //上传
    List<WorkBean.OverviewDOListBean> mList = new ArrayList<>();
    private OkgoNetwork mNetwork = new OkgoNetwork(this); //网络请求
    private TaskManageAdapter mAdapter;

    @Override
    public int setLayoutId() {
        return R.layout.activity_task_manage;
    }



    @Override
    public void initData() {
        super.initData();
        ButterKnife.bind(this);
        initRecyclerView();
        initTask();


    }
    //初始化rv
    private void initRecyclerView(){
        mRv.setLayoutManager(new LinearLayoutManager(this));
        mAdapter = new TaskManageAdapter(mList);
        mAdapter.setOnItemChildClickListener(this);
        mAdapter.openLoadAnimation(BaseQuickAdapter.SLIDEIN_RIGHT);
        mRv.setAdapter(mAdapter);
    }

    @OnClick({R.id.btn_download,R.id.tv_setting, R.id.btn_uploading ,R.id.tv_bluetooth,R.id.btn_delete})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_setting://设置用户 ip
                startActivity(new Intent(this, SettingActivity.class));
                break;
            case R.id.tv_bluetooth:
                //显示蓝牙对话框
                TaskBuletoothDialog dialog = new TaskBuletoothDialog();
                dialog.show(getSupportFragmentManager(),"" );
                break;
            case R.id.btn_download://下载任务
                String name = SharePreferenceUtils.getString(this,"username" ,"" );
                String ip = SharePreferenceUtils.getString(this,"ip" ,"" );
                if (TextUtils.isEmpty(name)){
                    MyToast.show("请在设置里填写姓名");
                } else  if(TextUtils.isEmpty(ip)){
                    MyToast.show("请在设置里填写服务器ip");
                }else {
                    showLoading("正在下载...");
                    mNetwork.download(this,mList ,name ,ip );
                }

                break;
            case R.id.btn_uploading:
                //上传
                upload();
                break;
            case R.id.btn_delete:
                //删除
                delete();
                break;
        }
    }

    //上传
    private void upload(){
        List<WorkBean.OverviewDOListBean> list = new ArrayList<>();
        //遍历选中的任务
        for (int i =0; i< mList.size() ; i++){
            if (mList.get(i).getMissionState() ==2){
                if (mList.get(i).isSelect()){
                    list.add(mList.get(i));
                    mList.get(i).setMissionState(3);
                }
            }
        }
        if (list.size() >0){
            showLoading("上传中...");
            String ip = SharePreferenceUtils.getString(this,"ip" ,"" );
            if (TextUtils.isEmpty(ip)){
                MyToast.show("请在设置里填写服务器ip");
            }
            mNetwork.upload(list ,ip,mList);
        }else {
            MyToast.show("没有要上传的任务");
        }
    }

   //删除任务
    private void delete(){
        List<WorkBean.OverviewDOListBean> list = new ArrayList<>();
        //遍历选中的任务
        for (WorkBean.OverviewDOListBean task: mList){
            if (task.getMissionState() ==3){
                if (task.isSelect()){
                    list.add(task);
                }
            }
        }
        if (list.size() >0){
            for (WorkBean.OverviewDOListBean task: list){
                 mList.remove(task);
            }
            showLoading("正在删除...");
            Observable.create(new ObservableOnSubscribe<Boolean>() {
                @Override
                public void subscribe(ObservableEmitter<Boolean> emitter) throws Exception {
                    Gson gson = new Gson();
                    //任务Json保存文件
                    emitter.onNext( FileUtils.writeFile(Constant.path+Constant.fileName, gson.toJson(mList), false));

                }
            }).subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Consumer<Boolean>() {
                        @Override
                        public void accept(Boolean s) throws Exception {
                            if (s){
                                mAdapter.replaceData(mList);
                                MyToast.show("删除成功");
                                }else {
                                MyToast.show("删除失败");
                            }
                            dismissLoading();
                        }
                    }, new Consumer<Throwable>() {
                        @Override
                        public void accept(Throwable throwable) throws Exception {
                            MyToast.show("删除任务出错");
                        }
                    });



    }else {
            MyToast.show("请选择要删除的任务");
        }
    }




    //加载任务列表
    private void initTask() {
        showLoading("加载数据...");
        Observable.create(new ObservableOnSubscribe<List<WorkBean.OverviewDOListBean>>() {
            @Override
            public void subscribe(ObservableEmitter<List<WorkBean.OverviewDOListBean>> emitter) throws Exception {
                //从文件读取任务json
                String json = FileUtils.readFile(Constant.path + Constant.fileName);
                //MyLogger.showLargeLog(json);
                if (TextUtils.isEmpty(json)){
                    emitter.onNext(mList);
                }else {
                    Gson gson = new Gson();
                    Type type = new TypeToken<List<WorkBean.OverviewDOListBean>>(){}.getType();
                    mList = gson.fromJson(json, type);
                    emitter.onNext(mList);//List<WorkBean.OverviewDOListBean>
                }

            }
                }).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new ObserverOnNext<List<WorkBean.OverviewDOListBean>>() {
                    @Override
                    public void onNext(List<WorkBean.OverviewDOListBean> overviewDOListBeans) {
                        if (overviewDOListBeans != null) {
                            //显示任务列表
                            mAdapter.replaceData(mList);
                        } else {
                            MyToast.show("没有数据");
                        }
                        dismissLoading();
                    }


                });


    }


    /**
     * 下载成功回调
     * @param list 任务
     */
    @Override
    public void download(List<WorkBean.OverviewDOListBean> list) {

        if (list != null){
          mAdapter.replaceData(list);
        }else {
         //MyToast.show("下载失败");
        }
        dismissLoading();
    }



    /**
     * 上传成功回调
     * @param bool  true 上传成功
     * @param files  图片
     */
    @Override
    public void uploadSuccess(boolean bool , final List<File> files) {

        if (bool){

               //上传图片
            if (files.size() >0) {
                String ip = SharePreferenceUtils.getString(this,"ip" ,"" );
                OkGo.<String>post("http://"+ip+"/app/open/uploadImg")
                        .tag(this)//
                        .isMultipart(true)
                        .addFileParams("files", files).execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        Gson gson = new Gson();
                        ImgBean bean = gson.fromJson(response.body(), ImgBean.class);
                        if (bean.getCode() == 0) {
                            MyToast.show("上传图片成功");
                        }else {
                            MyToast.show(bean.getMsg());
                            showDialogUpload(files);
                        }
                        dismissLoading();
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                            showDialogUpload(files);
                        MyToast.show(response.body());
                    }
                });
            }else {

            }

            mAdapter.notifyDataSetChanged();
            MyToast.show("上传任务成功");
        }else {
            MyToast.show("上传失败");
        }
        dismissLoading();

    }
    //重新上传图片
    private void showDialogUpload(final List<File> files){

        final AlertDialog.Builder normalDialog =
                new AlertDialog.Builder(this);
        normalDialog.setTitle("图片上传失败");
        normalDialog.setMessage("是否重新上传");
        normalDialog.setPositiveButton("确定",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        showLoading("正在上传图片");
                        String ip = SharePreferenceUtils.getString(TaskManageActivity.this,"ip" ,"" );
                        OkGo.<String>post("http://"+ip+"/app/open/uploadImg")
                                .tag(this)//
                                .isMultipart(true)
                                .addFileParams("files", files).execute(new StringCallback() {
                            @Override
                            public void onSuccess(Response<String> response) {
                                Gson gson = new Gson();
                                ImgBean bean = gson.fromJson(response.body(), ImgBean.class);
                                if (bean.getCode() == 0) {
                                    MyToast.show("上传成功");
                                }else {
                                   MyToast.show(bean.getMsg());
                                }
                                dismissLoading();
                            }

                            @Override
                            public void onError(Response<String> response) {
                                super.onError(response);
                                MyToast.show(response.body());
                            }
                        });

                    }
                });
        normalDialog.setNegativeButton("取消",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });
        normalDialog.show();

    }

    @Override
    public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
        WorkBean.OverviewDOListBean workTaskBean = mList.get(position);
        WorkTaskBean.getInstance().setList(mList);
        Intent intent = new Intent(this,MeasureActivity.class);
        switch (workTaskBean.getMissionState()){
            case 0://新任务

                intent.putExtra("data", workTaskBean);
                intent.putExtra("state", 0);
                startActivity(intent);
                finish();

                break;
            case 1://进行中
                intent.putExtra("id", workTaskBean.getRwgsId());
                intent.putExtra("state",1 );
                startActivity(intent);
                finish();
                break;
            case 2:
                MyToast.show("测量完成 待上传");
                break;
            case 3:
                MyToast.show("任务已完成");
                break;
        }


    }
}
